<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
          name="viewport"/>
    <title>Easy Manager</title>
    <link rel="stylesheet" href="css/app.css"/>
    <link rel="stylesheet" href="css/framework.css"/>
    <style>
        html, body {
            height: 100%;
            overflow: hidden;
            background: white;
            font-weight: 400;
        }

    </style>
</head>
<body>
<div id="app">
</div>
<div id="per-loader" class="loader">
    <div class="loader-inner"></div>
</div>
<script src="./css/iconfont.js"></script>
<script src="js/loader.min.js"></script>
<script src="js/framework.js"></script>
<script>
    require(['framework', 'vueRouter', 'Vuex'], ({ajax, Vue, init, axios, HeyUI}, VueRouter, Vuex) => {


        Vue.use(VueRouter)
        Vue.use(Vuex)

        let router = new VueRouter({
            routes: [
                {
                    path: '/login',
                    name: 'Login',
                    component: (r) => require(['login.vue'], r)
                },
                {
                    path: '/404',
                    name: '404',
                    component: (r) => require(['404.vue'], r)
                },
                {
                    path: '/',
                    name: 'Index',
                    component: (r) => require(['index.vue'], r),
                    children: [
                        // {
                        //     path: '/',
                        //     name: 'Home',
                        //     component: (r) => require(['home.vue'], r),
                        // }
                    ]
                },
                {
                    path: '*',
                    redirect: '/404',
                    name: 'notFound',
                    hidden: true
                }
            ]
        })
        const addRoutes = (menus) => {
            for (let menu of menus) {
                if (menu.children) {
                    addRoutes(menu.children)
                } else if (menu.path) {
                    if (menu.path.endsWith(".vue")) {
                        router.addRoute('Index', {
                            name: menu.key,
                            path: menu.key=="Home" ? "/":menu.key,
                            meta:{
                                title:menu.title
                            },
                            component: (r) => {
                                require([menu.path], r, (e) => {
                                    if (e.status == 404 || e.message=='Failed to fetch') {
                                        router.push("/404")
                                    }else{
                                        HeyUI.$Message({type:'error',text:e.statusText||e.message})
                                    }
                                })
                            }
                        })
                    } else {
                        router.addRoute({
                            name: menu.key,
                            path: menu.key,
                            meta:{
                              title:menu.title
                            },
                            props: {path: menu.path},
                            component: (r) => {
                                require(['coms/iframe.vue'], r)
                            }
                        })
                    }
                }
            }
        }
        const store = new Vuex.Store({
            state: {
                user: {},
                app: {}
            },
            actions: {
                loadUserInfo(ctx) {
                    return new Promise((resolve, reject) => {
                        ajax.get('system/user_info').then(r => {
                            addRoutes(r.data.menu)
                            ctx.state.user = r.data
                            // r.data.menu.unshift({
                            //     icon:'h-icon-home',
                            //     key:'Home',
                            //     title:'首页'
                            // })
                            resolve(r)
                            if (router.currentRoute.name == "Login") {
                                router.push('/')
                            }
                        }).catch(e => {
                            reject(e)
                        })
                    })
                }
            }
        })

        const whiteList = ['Login', '404', '403']
        router.beforeEach((to, from, next) => {
            let name = to.name
            if (whiteList.indexOf(name) > -1) {
                if (name == 'Login') {
                    let username = store.state.user.username
                    if (username) {
                        next('/')
                    } else {
                        next()
                    }
                } else {
                    next()
                }
            } else {
                let username = store.state.user.username
                if (!username) {
                    next('/login')
                } else {
                    next()
                }
            }
        })
        axios.interceptors.request.use(function(cfg){
            let token=sessionStorage['_token'];
            if(token){
                cfg.headers['token']=token
            }
            return cfg;
        })
        axios.interceptors.response.use(function (res) {
            if (res.headers['content-type'].indexOf('json')>-1 && res.data) {
                if(typeof(res.data)=='string'){
                    res.data=eval(res.data)
                }
                if(res.data.code==200){
                    let headers=res.headers
                    let token=headers['token'];
                    if(token){
                        sessionStorage.setItem("_token",token);
                    }else if(headers['rtk']){
                        sessionStorage.removeItem("_token")
                    }
                    return res.data;
                }
                //&& res.data.code != 200
                if (res.data.code == 401) {
                    store.state.user={}
                    location.hash = "/login"
                    return Promise.reject(res.data);
                }else if(res.data.code == 403){
                    HeyUI.$Message({type: 'error', text: "没有权限！"})
                    return Promise.reject(res.data);
                }
                HeyUI.$Message({type: 'error', text: res.data.description})
                return Promise.reject(res.data)
            } else {
                let headers=res.headers
                let token=headers['token'];
                if(token){
                    sessionStorage.setItem("_token",token);
                }else if(headers['rtk']){
                    sessionStorage.removeItem("_token")
                }
                return res.data;
            }
        }, function (error) {
            // 对响应错误做点什么;没有权限401，去登录界面
            if(!error.response){
                HeyUI.$Message({type: 'error', text: "网络错误！"})
                return
            }
            if (error.response.status === 401) {
                // window.$toast('登录超时')
                store.state.user={}
                location.hash = "/login"
            } else if (error.response.status === 403) {
                // window.$toast('暂无权限')
                HeyUI.$Message({type: 'error', text: "没有权限！"})
                location.hash = "/login"
            } else if (error.response.status === 500) {
                // window.$toast('网络错误')
                HeyUI.$Message({type: 'error', text: "服务器错误！"})
            } else if (error.response.status === 404) {
                // window.$toast('网络错误')
                HeyUI.$Message({type: 'error', text: "404 NOT FOUND！"})
            }
            return Promise.reject(error);
        });
        // ajax.get("system/dict").then(res=>{
        //     let data=res.data
        //     for(let it in data){
        //         let items=data[it]
        //         HeyUI.addDict(it,items);
        //     }
        // })
        store.dispatch('loadUserInfo').finally(e => {
            init("#app", {
                router,
                store
            })
        })
        // setInterval(() => {
        //     ajax.get("system/keep").then(r=>{
        //         if(r.data!=store.state.user.username){
        //             store.dispatch('loadUserInfo')
        //         }
        //     })
        // }, 20000)
    })
</script>

</body>
</html>
